package com.cljh.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.cljh.bean.*;
import com.cljh.controller.page.Code;
import com.cljh.controller.page.ValidationEnum;
import com.cljh.exception.SystemException;
import com.cljh.mapper.RoleMapper;
import com.cljh.mapper.RoleMenuMapper;
import com.cljh.service.*;
import com.cljh.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    UserService userService;
    @Autowired
    AdminService adminService;
    @Autowired
    ValidationService validationService;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RoleMenuMapper menuMapper;
    @Autowired
    MenuService menuService;
    @Value("${spring.mail.username}")
    private String from;

    @Override
    public Object loginEmail(Email email) {

        String username = email.getUsername();
        String emailCode = email.getEmail();
        String code = email.getCode();
        Validation validation = validationService.selectByEmail(emailCode);

        if (validation != null) {
            Date now = new Date();
            int type = validation.getType();
            Date time = validation.getTime();
            boolean res = now.getTime() > time.getTime();
            if (type == ValidationEnum.Login.getCode() && res) {
                throw new SystemException(Code.GET_ERR, "验证码过期请重新发送");
            }

            if (validation.getEmailCode().equals(code)){
                User user = userService.selectByEmail(username, emailCode);
                if (user!=null){
                    //设置token
                    String s = TokenUtils.genToken(user.getUsername(), user.getPwd());
                    user.setToken(s);
                    return user;
                }


                Admin admin = adminService.selectByEmail(username, emailCode);
                if (admin!=null){
                    //设置token
                    String s = TokenUtils.genToken(admin.getUsername(), admin.getPassword());
                    admin.setToken(s);

                    String role = admin.getRole();
                    int roleId=0;
                    if (!"".equals(role)){
                        Role role1 = roleMapper.selectByKey(role);
                        roleId=role1.getId();
                    }
                    //当前对象所有的菜单id集合
                    List<Integer> integers = menuMapper.selectByRoleId(roleId);

                    //列出所有菜单
                    List<Path> paths = menuService.selectAllPath();
                    //筛选出来的菜单
                    List<Path> roleMenus=new ArrayList<>();

                    for (Path p : paths) {
                        if(integers.contains(p.getId())){
                            roleMenus.add(p);
                        }
                        List<Path> children = p.getChildren();
                        //移除 children里面不在id的元素中
                        children.removeIf(child->!integers.contains(child.getId()));
                    }
                    admin.setMenus(roleMenus);
                    return admin;
                }
            }else {
                throw new SystemException(Code.GET_ERR,"验证码错误");
            }
        }
        return null;
    }

    @Override
    public void checkEmail(String email,Integer type1) {
        Validation validation = validationService.selectByEmail(email);
        Date now = new Date();
        if (validation != null) {
            int type = validation.getType();
            Date time = validation.getTime();
            boolean res = now.getTime() < time.getTime();
            if (type == type1 && res) {
                throw new SystemException(Code.GET_ERR, "当前您的验证码仍然有效，请不要重复发送");
            }

        }
        //一个简单的邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();

        String code = RandomUtil.randomNumbers(4);
        mailMessage.setFrom(from);
        mailMessage.setTo(email);
        mailMessage.setSentDate(now);
        if (ValidationEnum.Login.getCode().equals(type1)){
            mailMessage.setSubject("【名棠系统】登录邮箱验证");
            mailMessage.setText("本次的邮箱的验证码为:" + code + ",请妥善保管，切勿泄露.有效期为5分钟");
        }else if (ValidationEnum.FORGET_PASS.getCode().equals(type1)){
            mailMessage.setSubject("【名棠系统】找回密码邮箱验证");
            mailMessage.setText("本次的邮箱的验证码为:" + code + ",请妥善保管，切勿泄露.有效期为5分钟");
        }

        try {
            javaMailSender.send(mailMessage);
        } catch (MailSendException me) {
            me.printStackTrace();
        }


        validationService.saveCode(email, code, type1, DateUtil.offsetMinute(now, 5));
    }
    @Transactional
    @Override
    public boolean passUpd(Email item) {
        String email = item.getEmail();
        String code = item.getCode();

        Validation validation = validationService.selectByEmail(email);
        if (validation != null) {
            Date now = new Date();
            int type = validation.getType();
            Date time = validation.getTime();
            boolean res = now.getTime() > time.getTime();
            if (type == ValidationEnum.FORGET_PASS.getCode() && res) {
                throw new SystemException(Code.GET_ERR, "验证码过期请重新发送");
            }
            if (validation.getEmailCode().equals(code)){
                User user = userService.selectByEmailCode(email);
                Admin admin= adminService.selectByEmailCode(email);
                if (user!=null){
                    user.setPwd("123456");
                    return userService.update(user);
                }
                if (admin!=null){
                    admin.setPassword("123456");
                    return adminService.upd(admin);
                }
            }else {
                throw new SystemException(Code.GET_ERR,"验证码错误");
            }
        }
        return false;
    }

    @Override
    public String selectByEmailCode(String email) {
        User user = userService.selectByEmailCode(email);
        Admin admin= adminService.selectByEmailCode(email);
        if (user!=null){
            System.out.println(user.getUsername());
            return user.getUsername();
        }
        if (admin!=null){
            System.out.println(admin.getUsername());
            return admin.getUsername();
        }
        return null;
    }


}
